package com.ibmeeting.service.impl;

import com.ibmeeting.service.SmsService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.dromara.sms4j.api.SmsBlend;
import org.dromara.sms4j.comm.utils.SmsUtil;
import org.dromara.sms4j.core.factory.SmsFactory;
import org.dromara.sms4j.provider.enumerate.SupplierType;
import org.springframework.stereotype.Service;

import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Random;

@Service
@Slf4j
@RequiredArgsConstructor
public class SmsServiceImpl implements SmsService {

//    private final SmsBlend smsBlend; // SMS4J核心组件

    // 公共方法实现：发送验证码
    @Override
    public boolean sendVerificationCode(String configId, String phone, String code) {
        try {
            // 使用阿里云模板发送（需提前配置模板ID）
            SmsBlend alibabaSms = SmsFactory.createSmsBlend(SupplierType.ALIBABA);
//            SmsBlend alibabaSms = SmsFactory.getSmsBlend(SupplierType.ALIBABA);
            alibabaSms.sendMessage(phone, code);
            log.info("短信发送成功 - 手机号: {}, 验证码: {}", phone, code);
            return true;
        } catch (Exception e) {
            log.error("短信发送失败 - 手机号: {}, 原因: {}", phone, e.getMessage());
            return false;
        }
    }

    // 公共方法实现：发送模板短信
    @Override
    public boolean sendTemplateMessage(String phone, String templateId, Map<String, String> params) {
        try {
            // 转换为LinkedHashMap保持参数顺序
            LinkedHashMap<String, String> orderedParams = new LinkedHashMap<>(params);
            SmsBlend alibabaSms = SmsFactory.createSmsBlend(SupplierType.ALIBABA);
//            smsBlend.sendMessage(phone, templateId, orderedParams);
            return true;
        } catch (Exception e) {
            log.error("模板短信发送失败 - 模板ID: {}, 原因: {}", templateId, e.getMessage());
            return false;
        }
    }

    // 生成随机6位数字验证码
    @Override
    public String generateRandomCode(int length) {
         return SmsUtil.getRandomInt(6); // SMS4J内置工具
    }
}